package com.billdowney.util.zxing;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;

/**
 * @ClassName: ReadQRCode
 * @Description: 读取二维码工具类
 * @author 超级小富翁 - BillDowney
 * @date 2018年1月6日 下午6:18:48
 */
public class ReadQRCode {

	/**
	 * @Function: readQRCode
	 * @Description: 传入二维码文件路径读取内容
	 *
	 * @param filePath
	 *            二维码文件的绝对路径
	 * @return 识别过后的内容
	 *
	 * @author: 超级小富翁 - BillDowney
	 * @date: 2018年1月6日 下午6:14:44
	 */
	public static String readQRCode(String filePath) {
		String content = "";
		MultiFormatReader formatReader = new MultiFormatReader();
		File file = new File(filePath);
		BufferedImage image = null;
		try {
			image = ImageIO.read(file);
			BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
			// 定义二维码参数
			Map<DecodeHintType, Object> hints = new HashMap<>();
			hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
			Result result = formatReader.decode(binaryBitmap, hints);
			content = result.getText();
		} catch (Exception e) {
			e.printStackTrace();
			content = "";
		}
		return content;
	}

	/**
	 * @Function: readQRCode
	 * @Description: 传入一个含有二维码的BufferedImage对象识别内容
	 *
	 * @param bufferedImage
	 *            还有二维码的BufferedImage对象
	 * @return 识别的内容
	 *
	 * @author: 超级小富翁 - BillDowney
	 * @date: 2018年1月6日 下午6:17:51
	 */
	public static String readQRCode(BufferedImage bufferedImage) {
		String content = "";
		MultiFormatReader formatReader = new MultiFormatReader();
		try {
			BinaryBitmap binaryBitmap = new BinaryBitmap(
					new HybridBinarizer(new BufferedImageLuminanceSource(bufferedImage)));
			// 定义二维码参数
			Map<DecodeHintType, Object> hints = new HashMap<>();
			hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
			Result result = formatReader.decode(binaryBitmap, hints);
			content = result.getText();
		} catch (Exception e) {
			e.printStackTrace();
			content = "";
		}
		return content;
	}

}
